const app = getApp();

Page({
  data: {
    show: false,
    value: '',
    searchResults: [],
    loading: false,
    hasResults: true
  },
  
  onChange(event) {
    // 更新搜索关键词
    this.setData({ value: event.detail });
    
    // 当输入内容变化时，自动触发搜索
    if (event.detail.trim()) {
      this.onSearch();
    } else if (event.detail === '') {
      // 当输入框被清空时，清空搜索结果
      this.onClear();
    }
  },

  // 执行搜索
  onSearch() {
    const keyword = this.data.value.trim();
    if (!keyword) {
      wx.showToast({
        title: '请输入搜索关键词',
        icon: 'none'
      });
      return;
    }

    console.log('开始搜索，关键词：', keyword);
    this.setData({ loading: true });
    
    wx.request({
      url: app.globalData.URL + '/vCourse/getCourseByPage',
      method: 'GET',
      data: {
        pageNum: 1,
        pageSize: 100000,
        courseName: keyword
      },
      success: (res) => {
        console.log('搜索请求参数：', {
          pageNum: 1,
          pageSize: 100000,
          courseName: keyword
        });
        console.log('搜索结果原始数据：', res.data);
        
        if (res.data.code === 1) {
          const list = res.data.data.list || [];
          console.log('搜索到的课程数量：', list.length);
          
          // 处理图片路径和确保字段名称一致性
          const processedList = list.map((item, index) => {
            // 使用Object.assign替代对象展开语法
            const processedItem = Object.assign({}, item, {
              courseName: item.courseName || item.coursename,
              courseintroduce: item.courseintroduce || item.courseIntroduce || '',
              discountedPrice: item.discountedPrice || item.originalprice || 0
            });
            
            // 正确处理图片路径 - 同时处理两种可能的字段名
            const imageField = item.tabularchart || item.tabularChart;
            if (imageField) {
              processedItem.tabularchart = 'http://localhost:8080/file/downLoad?fileName=' + imageField;
            } else {
              processedItem.tabularchart = '/img/course/course.PNG'; // 默认图片
            }
            
            console.log(`课程${index + 1}:`, {
              id: processedItem.id,
              name: processedItem.courseName,
              price: processedItem.discountedPrice,
              intro: processedItem.courseintroduce,
              image: processedItem.tabularchart
            });
            
            return processedItem;
          });

          this.setData({
            searchResults: processedList,
            hasResults: processedList.length > 0
          });
        } else {
          console.log('搜索失败，接口返回错误：', res.data);
          this.setData({
            searchResults: [],
            hasResults: false
          });
          wx.showToast({
            title: '搜索失败，请重试',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('搜索请求网络错误：', err);
        this.setData({
          searchResults: [],
          hasResults: false
        });
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      },
      complete: () => {
        console.log('搜索请求完成');
        this.setData({ loading: false });
      }
    });
  },

  // 清空搜索
  onClear() {
    this.setData({
      value: '',
      searchResults: [],
      hasResults: true
    });
  },

  // 跳转到课程详情
  navigateToCourseDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/course/PsychologicalCounselorCourse/Psychological Counselor Course?id=${id}`
    });
  },

  showPopup() {
    this.setData({ show: true });
  },

  onClose() {
    this.setData({ show: false });
  }
});
